package whiteboard

import android.annotation.SuppressLint
import android.app.Activity
import android.app.ActivityManager
import android.content.Context
import android.content.Intent
import android.graphics.PixelFormat
import android.graphics.Point
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.provider.Settings
import android.view.*
import android.view.WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
import android.view.WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL
import android.widget.ImageView

class WhiteBoard : Activity(){
    lateinit var wm: WindowManager
    lateinit var manager: ActivityManager
    lateinit var wmParams: WindowManager.LayoutParams
    lateinit var fv: ImageView
    private lateinit var tasks: ActivityManager.AppTask
    private var iconSize = 0
    var vWidth = 0
    var vHeight = 0

    @SuppressLint("ClickableViewAccessibility")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        val outSize = Point()
        windowManager.defaultDisplay.getRealSize(outSize)
        vWidth = outSize.x
        vHeight = outSize.y

        iconSize = if(vWidth > vHeight)
            vHeight / 10
        else
            vWidth / 10

        val graView = object: GraView(this, vWidth, vHeight){
            override fun exitGra(){
                this.gra.clear()
                moveTaskToBack(true)
            }
        }

        setContentView(graView)
        moveTaskToBack(true)

        manager = getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (!Settings.canDrawOverlays(this))
                startActivityForResult(Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:$packageName")), 0)
            else
                init()
        }

        fv = ImageView(applicationContext)
        fv.run {
            layoutParams = ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT)
            setImageResource(R.drawable.pen)
            setOnClickListener {
                window.decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_FULLSCREEN or
                        View.SYSTEM_UI_FLAG_HIDE_NAVIGATION or
                        View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or
                        View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION or
                        View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
                tasks.moveToFront()
            }
        }
        var x = 0f
        var y = 0f
        fv.setOnTouchListener { _, e ->
            when(e.action) {
                MotionEvent.ACTION_DOWN -> {
                    x = e.rawX
                    y = e.rawY
                }
                MotionEvent.ACTION_MOVE -> {
                    wmParams.x += (e.rawX - x).toInt()
                    wmParams.y += (e.rawY - y).toInt()
                    wm.updateViewLayout(fv, wmParams)
                    x = e.rawX
                    y = e.rawY
                }
            }
            return@setOnTouchListener false
        }
    }

    private fun init(){
        wm =  windowManager
        wmParams = WindowManager.LayoutParams()
        wmParams.run {
            format = PixelFormat.RGBA_8888
            flags = FLAG_NOT_TOUCH_MODAL or FLAG_NOT_FOCUSABLE
            gravity = Gravity.LEFT or Gravity.TOP
            x = vWidth - iconSize
            y = (vHeight - iconSize) / 2
            width = iconSize
            height = iconSize
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
            wmParams.type = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY
        else
            wmParams.type = WindowManager.LayoutParams.TYPE_PHONE
    }

    override fun onStop() {
        wm.addView(fv, wmParams)
        tasks = manager.appTasks.last()
        super.onStop()
    }

    override fun onRestart() {
        wm.removeViewImmediate(fv)
        super.onRestart()
    }

    override fun onDestroy() {
        wm.removeViewImmediate(fv)
        super.onDestroy()
    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        if(keyCode == KeyEvent.KEYCODE_BACK)
            return true
        return super.onKeyDown(keyCode, event)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if(requestCode == 0){
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
                if (Settings.canDrawOverlays(this))
                    init()
        }
    }
}
